/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ListView
} from 'react-native';

var API_KEY = '7waqfqbprs7pajbz28mqf6vz';
var API_URL = 'http://api.rottentomatoes.com/api/public/v1.0/lists/movies/in_theaters.json';
var PAGE_SIZE = 25;
var PARAMS = '?apikey=' + API_KEY + '&page_limit=' + PAGE_SIZE;
var REQUEST_URL = API_URL + PARAMS;

//伪造数据
const MOVIES_DATA = [
    {
        title: 'Title',
        year: '2015',
        posters: {
            thumbnail: 'https://i.imgur.com/UePbdph.jpg'
        }
    }
];

//组件开始
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2
            }),
            loading: true
        };

    }

    componentDidMount() {
        this.fetchData();
    }

    fetchData() {

        fetch(REQUEST_URL).then((response) => response.json()).then((responseData) => {
            this.setState({
                dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
                loading: false
            });
        }).done();

    }

    renderLoadingView() {
        return (
            <View style={styles.container}>
                <Text>
                    Loading movies...
                </Text>
            </View>
        );
    }

    renderMovie(movie) {
        return (
            <View style={styles.container}>
                <Image source={{
                    uri: movie.posters.thumbnail
                }} style={styles.thumbnail}/>
                <View style={styles.rightContainer}>
                    <Text style={styles.title}>{movie.title}</Text>
                    <Text style={styles.year}>{movie.year}</Text>
                </View>
            </View>
        );
    }

    render() {
        if (this.state.loading) {
            return this.renderLoadingView();
        }

        return (<ListView dataSource={this.state.dataSource} renderRow={this.renderMovie} style={styles.listView}/>);
    }
}

//样式表
const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF'
    },
    listView: {
        backgroundColor: '#F5FCFF'
    },
    thumbnail: {
        width: 50,
        height: 50
    },
    rightContainer: {
        flex: 1
    },
    title: {
        fontSize: 20,
        marginBottom: 8,
        textAlign: 'center'
    },
    year: {
        textAlign: 'center'
    }
});

//注册组件
AppRegistry.registerComponent('jstapp', () => App);
